﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TVGuide.Enums;
using TVGuide.DataAccess.Common;
using TVGuide.DataAccess.Repository;
using TVGuide.Common;
using TVGuide.DataAccess;
using System.Data;
using System.Text.RegularExpressions;

namespace TvGuide.UI.Models
{
    public class ProgramData
    {
        public int ZoneHour = Utils.ZoneHour;
        private CommonStr comm_str;
        private int lang;
        private List<ProgCategory> CatList;
        private DbAccessHelper access_helper = new DbAccessHelper(); 
        // s public List<ProgsShowList> ProgsList { get; set; }
        public string ProgsListHtml { get; set; }

        public List<NowRunningProg> NowRunnList = new List<NowRunningProg>();
        public List<ChannelShowList> ChList { get; set; }
        public static List<ChannelShowList> chlist;
        public int ChID { get; set; }
        public string ChFbImg { get; set; }
        public string OnAirVal { get; set; }
        public string MetaDescription { get; set; }

        public int WeekDayID { get; set; }
        public List<string> weekDays = new List<string>() { "", "", "", "", "", "", "", "" };
        public List<string> WeekDay { get { return this.weekDays; } }
        public string Onair;

        public List<ProgCategory> Catlist
        {
            get { return this.CatList; }
        }

        public CommonStr Comm_str
        {
            get { return comm_str; }
        }

        public int Lng
        {
            get { return this.lang;}
        }

        public string OnAir
        {
            get {return this.Onair;}
        }

        public List<double> NowRunProgsCompletePersList { get; set; }
        public List<short> NowRunProgsPassedMinList { get; set; }

        static ProgramData()
        {
            chlist = InitChannelsList();
        }

        public ProgramData(int lng)
        {
            this.lang = lng;
           // this.ChList = new List<ChannelShowList>();
            this.ChList = chlist;
            this.comm_str = new CommonStr(ResUtil.GetLang(lng));
            this.comm_str = new CommonStr(ResUtil.GetLang(lng));
            CategoryInit(lng);
        }

        private static List<ChannelShowList> InitChannelsList()
        {
            List<ChannelShowList> CurrChShowList = new List<ChannelShowList>();
            int error_code;
            DbAccessHelper localHelper = new DbAccessHelper();
            DataTable dt = localHelper.GetAllChannels(out error_code);
            if (error_code != 0)
                return CurrChShowList;

            
            foreach (DataRow dr in dt.Rows)
            {
                if (Convert.ToInt16(dr["enabled"]) > 0)
                    CurrChShowList.Add(new ChannelShowList() { 
                        Name = Convert.ToString(Utils.ConvertDbNulls(dr["channelName"])), 
                        DispName = Convert.ToString(Utils.ConvertDbNulls(dr["displayName"])), 
                        ID = Convert.ToInt32(dr["channelID"]),
                        CatID = Convert.ToInt32(Utils.ConvertDbNulls(dr["categoryID"])), 
                        ImgUrl = Convert.ToString(Utils.ConvertDbNulls(dr["imgUrl"])),
                        FBImgUrl = Convert.ToString(Utils.ConvertDbNulls(dr["fbImgUrl"])), 
                        StreamUrl = Convert.ToString(Utils.ConvertDbNulls(dr["channelStreamUrl"])),
                        MetaDescription = Convert.ToString(Utils.ConvertDbNulls(dr["MetaDescription"])),
                        TorrentContentID = Convert.ToString(Utils.ConvertDbNulls(dr["torrentContentID"]))
                    });
            }

            //var DataAcc = ChannelRepository.Instance();
            //foreach (var ch in DataAcc.GetAllItems())
            //{
            //    if (ch.Enabled > 0)
            //        CurrChShowList.Add(new ChannelShowList() { Name = ch.Name, DispName = ch.DisplayName, ID = ch.Id, ImgUrl = ch.ImageURL });
            //}

            return CurrChShowList;
        }

        private void CategoryInit(int lng)
        {
            this.CatList = new List<ProgCategory>();
            int error_code;
            DataTable dt = access_helper.GetAllCategory(out error_code);
            if (error_code != 0)
                return;

            foreach (DataRow dr in dt.Rows)
                this.CatList.Add(new ProgCategory() { color = "#" + Convert.ToString(Utils.ConvertDbNulls(dr["color"])), CatId = Convert.ToInt16(dr["catID"]), CatName = Convert.ToString(Utils.ConvertDbNulls(dr["catName"])), CatDispName = setCatdispName(Convert.ToInt16(dr["catID"])) });

            //var cat = CategoryRepository.Instance().Get(o=>o.Priority!=null).OrderBy(o=>o.Priority);
            //foreach (var category in cat)
            //    this.CatList.Add(new ProgCategory() { color = "#"+category.Color, CatId = category.Id, CatName = category.Name, CatDispName = setCatdispName(category.Id) });
        }

        private string setCatdispName(short id)
        {
            string name = "";
            switch (id)
            {
                case 1:
                    name = this.comm_str.NEWS_LBL;
                    break;
                case 2:
                    name = this.comm_str.FILMS_LBL;
                    break;
                case 3:
                    name = this.comm_str.MUSIC_LBL;
                    break;
                case 4:
                    name = this.comm_str.CHILDREN_LBL;
                    break;
                case 5:
                    name = this.comm_str.SPORT_LBL;
                    break;
                case 8:
                    name = this.comm_str.HUMOR_LBL;
                    break;
                
            }
            return name;      
        }
       
        public void ProgramsList(DateTime date, int ch,int? lineindex)
        {
           
            string datestr = date.Day.ToString() + "." + date.Month.ToString() + "." + date.Year.ToString();
            int shareid = (int)((date - DateTime.Now.AddHours(Utils.ZoneHour)).TotalDays) + 1;
            List<ProgsShowList> CurrShowList = new List<ProgsShowList>();
           // var DataAcc = ProgramRepository.Instance();
            string chDispName = chlist.Find(o=>o.ID==ch).DispName;
            chDispName = TranslateToCurrentLang(chDispName);
            String channelName = chlist.Find(o=>o.ID==ch).Name;
            string chImageURL = chlist.Find(o=>o.ID==ch).ImgUrl;
            int catId = chlist.Find(o => o.ID == ch).CatID;
            string chFBImageURL = chlist.Find(o => o.ID == ch).FBImgUrl;
            this.ChFbImg = chFBImageURL;
            String onlineViewUrl = chlist.Find(o => o.ID == ch).StreamUrl;
            string onlinePageUrl = "/" + Utils.LanguageSelectToString(this.lang) + "/Watch/" + channelName+"-tv-online";
            DateTime CompareDate;
            if(date.Hour >= 0 && date.Hour <= 8)
                CompareDate = new DateTime(date.Year, date.Month, date.Day-1, 8, 0, 0);
            else
                CompareDate = new DateTime(date.Year, date.Month, date.Day, 8, 0, 0);

            int error_code;
            DataTable dt = access_helper.GetProgramsWithSpecChannel(out error_code, ch, CompareDate, CompareDate.AddHours(24));
            if (error_code != 0)
                return;

           // var CurrList = DataAcc.Get(o => o.ChannelId == ch && o.Date >= CompareDate && o.Date < CompareDate.AddHours(24)).ToList();
            int? differInd = null;
            int index = 0;

            foreach (DataRow dr in dt.Rows)
            {
                if (date.DayOfYear == DateTime.Now.AddHours(Utils.ZoneHour).DayOfYear && index < dt.Rows.Count && DateTime.Now.AddHours(Utils.ZoneHour) >= Convert.ToDateTime(dr["date"]) && DateTime.Now.AddHours(Utils.ZoneHour) < Convert.ToDateTime(dt.Rows[index + 1]["date"]))
                    differInd = index;
                if (index < (dt.Rows.Count - 1) && date.DayOfYear == DateTime.Now.AddHours(Utils.ZoneHour).DayOfYear && index < dt.Rows.Count && DateTime.Now.AddHours(Utils.ZoneHour).AddDays(1) >= Convert.ToDateTime(dr["date"]) && DateTime.Now.AddHours(Utils.ZoneHour).AddDays(1) < Convert.ToDateTime(dt.Rows[index + 1]["date"]))
                    differInd = index;

                index++;
                CurrShowList.Add(new ProgsShowList() { CatID = Convert.ToInt16(Utils.ConvertDbNulls(dr["categoryID"])), Name = Convert.ToString(Utils.ConvertDbNulls(dr["title"])), Time = string.Format("{0:d2}", Convert.ToDateTime(dr["date"]).Hour + ":" + string.Format("{0:d2}", Convert.ToDateTime(dr["date"]).Minute)), Date = Convert.ToDateTime(dr["date"]) });
            }

            
            System.Text.StringBuilder StrHtml = new System.Text.StringBuilder();
            // this.ProgsList = CurrShowList;
            if (CurrShowList.Count == 0)
                return;

            // TItle row construction
            //StrHtml.Append(string.Format("<table id='listing_table' class='Home-page_Prog_listing' CELLSPACzING=0><tr><td class='Home-page_Prog_Div_Programs_Title' colspan='4'><span class='Home-page_Prog_Div_Programs_Progname_Span'>{0}</span><span class='Home-page_Prog_Div_Programs_Date'>{1}</span></td></tr>", ChName, date.ToShortDateString()));
            StrHtml.Append("<table id='listing_table' class='Home-page_Prog_listing' CELLSPACING=0><tr>");
            
            // Channel Title uses colspan 4
            StrHtml.Append("<td class='Home-page_Prog_Div_Programs_Title' colspan='4'>");

            // Channel Title
            StrHtml.Append(String.Format("<span class='Home-page_Prog_Div_Programs_Progname_Span'><h2>{0}</h2></span>", chDispName));
            // Current Date
            StrHtml.Append(String.Format("<span class='Home-page_Prog_Div_Programs_Date'>{0}</span>", date.ToShortDateString()));
            StrHtml.Append("</td></tr>");


            for (int i = 0; i < index; i++)
            {
                string aaa = HttpUtility.HtmlEncode(CurrShowList[i].Name);
                string time = CurrShowList[i].Time;
                string HTMLencodedName = HttpUtility.HtmlEncode(CurrShowList[i].Name);
                //Format("{0:g}", dt) "3/9/2008 4:05 PM"                ShortDate+ShortTime
                string HTMLdecodedName = TranslateToCurrentLang(HttpUtility.HtmlDecode(CurrShowList[i].Name));
                string feedText = HttpUtility.HtmlDecode(String.Format("{0:d/MM HH:mm}", CurrShowList[i].Date)) + " - " + HTMLdecodedName;
                string chName = TranslateToCurrentLang(chDispName);
                string CatId = CurrShowList[i].CatID==null?"":"Category_"+CurrShowList[i].CatID.ToString();
                string querry = "";
                string kinopoiskURL = "";
                // Check if program is a film, create a link to Kinopoisk, 2=Film
                if (catId == 2 && HTMLdecodedName.IndexOf('-')!=-1)
                {
                    if (HTMLdecodedName.IndexOf('(')!=-1 && (HTMLdecodedName.IndexOf('(')<HTMLdecodedName.IndexOf('-')))
                    {
                         querry = HTMLdecodedName.Substring(0, HTMLdecodedName.IndexOf('('));
                    }
                    else
                    {
                        querry = HTMLdecodedName.Substring(0, HTMLdecodedName.IndexOf('-'));
                    }
                    // Try to get a year m_act[year]
                    string yearPatt = @"(\d\d\d\d)г?";
                    Regex rgx = new Regex(yearPatt, RegexOptions.IgnoreCase);
                    Match match = rgx.Match(HTMLdecodedName);
                    if (match.Success)
                    {
                        kinopoiskURL = "http://www.kinopoisk.ru/index.php?first=yes&what=&kp_query=" + querry + "&m_act[year]=" + match.Groups[1];
                    }
                    else
                    {
                        kinopoiskURL = "http://www.kinopoisk.ru/index.php?first=yes&what=&kp_query=" + querry;
                    }
                    
                    
                    
                }

                string twitlink = HttpUtility.HtmlEncode("http://twitter.com/intent/tweet?text=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "/http://www.tvcuyc.am/" + "&redirect_uri=http://tvcuyc.am/close.html"); // link=http://tvcuyc.am/" + ch + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + chImageURL + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" at " + time + " on " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                string link = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945&display=popup&link=http://tvcuyc.am/" + Utils.LanguageSelectToString(this.lang) + "/Share/" + ch + "/" + (shareid * 100 + i) + "&picture=http://tvcuyc.am" + chFBImageURL + "&name=" + feedText + "&redirect_uri=http://tvcuyc.am/close.html");
                if (differInd != null)
                {
                    if (i == differInd)
                    {
                        if (catId == (short)TVGuide.Enums.Categories.FILMS) // Channel is film channel
                        {
                            if (String.IsNullOrEmpty(onlineViewUrl))
                            {
                                HTMLdecodedName = "<a rel='nofollow' style='color:#ffffff' class='Home-page_Film_Click' target='_blank' href='" + kinopoiskURL + "'>" + HTMLdecodedName + "</a>";
                            }
                            else
                            {
                                HTMLdecodedName = "<a style='color:#ffffff' class='Home-page_Film_Click' target='_blank' href='" + onlinePageUrl + "'>" + HTMLdecodedName + "</a>";
                            }
                            
                        }
                        if (!String.IsNullOrEmpty(onlineViewUrl))
                        {
                            HTMLdecodedName = "<a style='color:#ffffff' class='Home-page_Film_Click' target='_blank' href='" + onlinePageUrl + "'>" + HTMLdecodedName + "</a>";
                        }
                        
                        StrHtml.Append("<tr class='Home-page_Prog_onAir " + CatId + "'><td><input type='hidden' class='progcathiden' value ='"+CatId+"'/> " + time + " </td><td> <h3>" + HTMLdecodedName + "</h3> </td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='Armenia TV' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='Armenia TV' border='0' /> </a></td></tr>");
                        continue;
                    }
                    else if (catId == (short)TVGuide.Enums.Categories.FILMS)
                    {
                        HTMLdecodedName = "<a rel='nofollow' class='Home-page_Film_Click' target='_blank' href='" + kinopoiskURL + "'>" + HTMLdecodedName + "</a>";
                    }


                }
                else if (catId == (short)TVGuide.Enums.Categories.FILMS)
                {
                    HTMLdecodedName = "<a rel='nofollow' class='Home-page_Film_Click' target='_blank' href='" + kinopoiskURL + "'>" + HTMLdecodedName + "</a>";
                }

                if (lineindex != null && lineindex == i)
                {
                    StrHtml.Append("<tr class='Home-page_Prog_onShare " + CatId + "'><td><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + time + " </td><td> <h3>" + HTMLdecodedName + "</h3> </td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='Armenia TV' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='Armenia TV' border='0' /> </a></td></tr>");
                    continue;
                }

                if (i % 2 == 0)
                    StrHtml.Append("<tr class='Home-page_Prog_listing_darker " + CatId + "'><td class='Home-page_Prog_listing_time'><input type='hidden' class='progcathiden' value ='" + CatId + "'/> " + time + " </td><td class='Home-page_Prog_listing_name'> <h3>" + HTMLdecodedName + "</h3> </td><td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' href ='" + link + "' onclick=\"return popitup('" + link + "')\" ><img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='Armenia TV' border='0' /> </a></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='Armenia TV' border='0' /> </a></td></tr>");

                else
                    StrHtml.Append("<tr class='Home-page_Prog_listing_lighter " + CatId + "'><td class='Home-page_Prog_listing_time'> <input type='hidden' class='progcathiden' value ='" + CatId + "'/>" + time + "</td><td class='Home-page_Prog_listing_name'> <h3>" + HTMLdecodedName + "</h3> </td><td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' target='_blank' href ='" + link + "' onclick=\"return popitup('" + link + "')\"> <img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='Armenia TV' border='0' /></a></td></td><td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='Armenia TV' border='0' /> </a></td></tr>");
            }
            StrHtml.Append("</table>");

            this.ProgsListHtml = StrHtml.ToString();

        }

        public void NowRuning(DateTime date, string lng)
        {
          //  if (date.Hour >= 0 && date.Hour <= 5)
          //      date = date.AddHours(-5);
            SetOnAirVal(date);
            string datestr = date.Day.ToString() + "." + date.Month.ToString() + "." + date.Year.ToString();
            int shareid = (int)((date - DateTime.Now.AddHours(Utils.ZoneHour)).TotalDays) + 1;
            DateTime dategr =  date.AddHours(4.5);
            DateTime dateles = date.AddHours(-4.5);

            int error_code;
            DataTable dt = access_helper.GetProgramsWithChannelSpecDate(out error_code, dategr, dateles);
            if (error_code != 0)
                return;

            NowRunnList = new List<NowRunningProg>();
            foreach (DataRow dr in dt.Rows)
                NowRunnList.Add(new NowRunningProg() { CategoryId = Convert.ToInt16(Utils.ConvertDbNulls(dr["categoryId"])), ChdispName = Convert.ToString(Utils.ConvertDbNulls(dr["chandisplayname"])), chID = Convert.ToInt32(dr["chanid"]), ChimgUrl = Convert.ToString(Utils.ConvertDbNulls(dr["chanimgurl"])), ChName = Convert.ToString(Utils.ConvertDbNulls(dr["channame"])), Date = Convert.ToDateTime(dr["prdate"]), PrName = Convert.ToString(Utils.ConvertDbNulls(dr["prname"])), viewlink = Convert.ToString(Utils.ConvertDbNulls(dr["chanstream"])), FBImgUrl = Convert.ToString(Utils.ConvertDbNulls(dr["fbimgurl"])) });

            //var NowRunnList = (from Progs in ProgramRepository.Instance().Get(o => (o.Date < dategr && o.Date > dateles) )
            //                   from Chan in ChannelRepository.Instance().GetAllItems()
            //                   where Progs.ChannelId == Chan.Id
            //                   orderby Chan.Enabled
            //                   select new {Progs.CategoryId, Progs.Date, PrName = Progs.Name, ChName = Chan.Name, ChdispName = Chan.DisplayName, chID = Progs.ChannelId, ChimgUrl = Chan.ImageURL, viewlink = Chan.ChannelStreamUrl}).ToList();


            //var NowRunnList = (from Progs in ProgramRepository.Instance().Get(o => (o.Date < dategr && o.Date > dateles))
            //                   from Chan in ChannelRepository.Instance().GetAllItems()
            //                   where Progs.ChannelId == Chan.Id
            //                   orderby Chan.Enabled
            //                   select new { Progs.CategoryId, Progs.Date, PrName = Progs.Name, ChName = Chan.Name, ChdispName = Chan.DisplayName, chID = Progs.ChannelId, ChimgUrl = Chan.ImageURL, viewlink = Chan.ChannelStreamUrl }).ToList();

            if (NowRunnList.Count() == 0)
            {
                this.ProgsListHtml = "";
                return;
            }
            if (NowRunnList.Count == 0)
            {
                this.ProgsListHtml = "";
                return;
            }

            string chname, nextchname;
            DateTime stdate, enddate;

            List<int> nowRunProgsDisplayList = new List<int>();
            NowRunProgsCompletePersList = new List<double>();
            NowRunProgsPassedMinList = new List<short>();

            for (int i = 0; i < NowRunnList.Count; i++)
            {
                chname = NowRunnList[i].ChName;
                stdate = NowRunnList[i].Date;
                if(i < NowRunnList.Count - 2)
                {
                    enddate = NowRunnList[i+1].Date;
                    nextchname = NowRunnList[i+1].ChName;
                }
                else
                {
                    enddate = NowRunnList[i].Date;                    
                    nextchname = NowRunnList[i].ChName;
                }
                if (stdate <= date && enddate >= date && chname == nextchname)
                {
                    nowRunProgsDisplayList.Add(i);
                    // Obtaining now running program's completement percentage
                    if ((date - stdate).TotalMinutes != 0)
                    {
                        NowRunProgsCompletePersList.Add(100 * (date - stdate).TotalMinutes / (enddate - stdate).TotalMinutes);
                        NowRunProgsPassedMinList.Add(Convert.ToInt16((date - stdate).TotalMinutes));
                    }
                    else
                    {
                        NowRunProgsCompletePersList.Add(0);
                        NowRunProgsPassedMinList.Add(0);
                    }

                    for(int j = i+1;j < NowRunnList.Count; j++)
                        if(j<NowRunnList.Count-2 && NowRunnList[j].ChName!=NowRunnList[j+1].ChName)
                        {
                            i = j;
                            break;
                        }
                }
            }
            System.Text.StringBuilder StrHtml = new System.Text.StringBuilder();
            StrHtml.Append(string.Format("<table id='listing_table' class='Home-page_Prog_listing' CELLSPACING=0><tr><td class='Home-page_Prog_Div_Programs_Title' colspan='6'>{0}<span class='Home-page_Prog_Div_Programs_Date'>{1}</span></td></tr>", "", date.ToShortDateString()));
            for (int i = 0; i < nowRunProgsDisplayList.Count; i++)
            {
                string onlinelink = NowRunnList[nowRunProgsDisplayList[i]].viewlink;
              //  string aaa = HttpUtility.HtmlEncode(NowRunnList[i].PrName);
                string time = string.Format("{0:d2}", NowRunnList[nowRunProgsDisplayList[i]].Date.Hour) + ":" + string.Format("{0:d2}", NowRunnList[nowRunProgsDisplayList[i]].Date.Minute);
                string HTMLencodedName = HttpUtility.HtmlEncode(NowRunnList[nowRunProgsDisplayList[i]].PrName);
                string HTMLdecodedName =  TranslateToCurrentLang(HttpUtility.HtmlDecode(NowRunnList[nowRunProgsDisplayList[i]].PrName));
                string feedText = HttpUtility.HtmlDecode(String.Format("{0:d/MM HH:mm}", NowRunnList[nowRunProgsDisplayList[i]].Date)) + " - " + HTMLdecodedName;
                string chName = TranslateToCurrentLang(NowRunnList[nowRunProgsDisplayList[i]].ChdispName);
                string churl = NowRunnList[nowRunProgsDisplayList[i]].ChimgUrl;
                string CatId = NowRunnList[nowRunProgsDisplayList[i]].CategoryId == null ? "" : "Category_" + NowRunnList[nowRunProgsDisplayList[i]].CategoryId.ToString();
                string stremUrl = NowRunnList[nowRunProgsDisplayList[i]].viewlink;
                string url = "http://tvcuyc.am/" + Utils.LanguageSelectToString(this.lang) + "/Share/" + NowRunnList[nowRunProgsDisplayList[i]].chID + "/" + (shareid * 100 + i);
                if (!String.IsNullOrEmpty(stremUrl))
                {
                    url = "http://tvcuyc.am/" + Utils.LanguageSelectToString(this.lang) + "/Watch/" + NowRunnList[nowRunProgsDisplayList[i]].ChName+ "-tv-online";
                }

                

                string twitlink = HttpUtility.HtmlEncode("http://twitter.com/intent/tweet?text=I am going to watch " + "\"" + HTMLdecodedName + "\" on " + datestr + " at " + time + " by " + chName + "/http://www.tvcuyc.am/" + "&redirect_uri=http://tvcuyc.am/close.html"); // link=http://tvcuyc.am/Home/Home/" + ch + "/" + (shareid * 100 + i) + "/1&  picture=http://tvcuyc.am" + chImageURL + "& name=Armenian TV programs schedule Online& caption=tvcuyc.am&  description=& message=I am going to watch " + "\"" + HTMLdecodedName + "\" at " + time + " on " + chName + "&redirect_uri=http://tvcuyc.am/close.html");
                string link = HttpUtility.HtmlEncode("http://www.facebook.com/dialog/feed?app_id=197849216924945&display=popup&link=" + url + "&picture=http://tvcuyc.am" + NowRunnList[nowRunProgsDisplayList[i]].FBImgUrl + "&name=" + feedText + "&caption=tvcuyc.am&redirect_uri=http://tvcuyc.am/close.html");

                //  <td class=''><img src='" + churl + "'alt ='" + chName + "'> </td>
                string onlineview="";
                if (!String.IsNullOrEmpty(onlinelink))
                    onlineview = " <a alt='Օնլայն TV" + chName + "'   target=\"_blank\"  href='/" + TVGuide.Common.Utils.LanguageSelectToString(this.Lng) + "/Watch/" + NowRunnList[nowRunProgsDisplayList[i]].ChName + "-tv-online' ><img width='20px' style='margin-top:4px' alt='Armenia tv " + chName + "' src='/Content/onlineview.png' ></img> </a> ";

                chName = "<a style='color:#D95505' class='Home-page_Film_Click' href='/" + TVGuide.Common.Utils.LanguageSelectToString(this.Lng) + "/schedule/" + NowRunnList[nowRunProgsDisplayList[i]].ChName + "-tv/" + NowRunnList[nowRunProgsDisplayList[i]].chID + "/1'>" + chName + "</a>";
                List<String> tdCreator = new List<string>();
                // online view td 
                tdCreator.Add("<td class='Home-page_Prog_listing_Chanal_onlineView'> " + onlineview + " </td>");
                // channel name td
                tdCreator.Add("<td class='Home-page_Prog_listing_Chanal'><input type='hidden' class='progcathiden' value ='" + CatId + "'/> <h3>" + chName + "</h3> </td>");
                // time td
                tdCreator.Add("<td class='Home-page_Prog_listing_time_Now'> " + time + " </td>");
                // prog name td
                tdCreator.Add("<td class='Home-page_Prog_listing_name_Now'> " + HTMLdecodedName + " </td>");
                // progress bar td
                if (date.Second != 0 && date.Millisecond != 0)
                {
                    string progressbarTooltip = lng == "eng" ? "Passed {0} min" : "Անցել է {0} րոպե";
                    tdCreator.Add("<td title='" + string.Format(progressbarTooltip, NowRunProgsPassedMinList[i]) + "' class='progress-bar-now'><div id='progressbar_" + i + "'></div></td>");
                }
                else
                    tdCreator.Add("<td class='progress-bar-now'><div id='progressbar_" + i + "'></div></td>");
                    // empty separator
                    tdCreator.Add("<td class='progress-bar-separator'><div></div></td>");
                // fb td
                tdCreator.Add("<td class='td_share_btn' class='Home-page_Prog_listing_FBStatus'><a target='_blank' class='a_fb_btn' href ='" + link + "' onclick=\"return popitup('" + link + "')\" ><img class='fb_share' src='http://tvcuyc.am/Content/imgs/fb_share.gif' alt='Armenia TV' border='0' /> </a></td>");
                // twitter td
                tdCreator.Add("<td class='td_share_btn'><a class='a_fb_btn' target='_blank' href ='" + twitlink + "' onclick=\"return popitup('" + twitlink + "')\"> <img class='tw_share' src='http://tvcuyc.am/Content/imgs/tw_share.gif' alt='Armenia TV' border='0' /> </a></td>");
                
                // Row creation 
                if (i % 2 == 0)
                    StrHtml.Append("<tr class='Home-page_Prog_listing_darker " + CatId + " '>");
                else
                    StrHtml.Append("<tr class='Home-page_Prog_listing_lighter " + CatId + " '>");                
                foreach (String TD in tdCreator)
                {
                    StrHtml.Append(TD);
                }
                StrHtml.Append("</tr>");
                
            }
            StrHtml.Append("</table>");


            this.ProgsListHtml = StrHtml.ToString();

        }

        public string TranslateToCurrentLang(string content)
        {
            switch (lang)
            {
                case 2:
                    return Utils.armToEngChar(Utils.ruToEngChar(content));                    
                default:
                    return content;                    
            }
        }

        private void SetOnAirVal(DateTime date)
        {
            this.OnAirVal = string.Format("{0:d2}", date.Hour) + ":" + string.Format("{0:d2}", date.Minute);
        }

        public static DateTime SetOnAirDate(int? val)
        {
            DateTime tocount = DateTime.Now.AddHours(Utils.ZoneHour);
            DateTime stdate = new DateTime(tocount.Year, tocount.Month, tocount.Day, 8, 0, 0);
            if (val == null)
                return DateTime.Now.AddHours(Utils.ZoneHour);
            return stdate.AddHours(((int)val) / 2).AddMinutes(((int)val % 2) * 30);
        }

        public static DateTime GetPrDate(ref int? id)
        {
            DateTime date = DateTime.Now.AddHours(Utils.ZoneHour);
            date = DateTime.Now.AddHours(Utils.ZoneHour).AddDays((int)id - 1);
         //   if (date.Hour >= 0 && date.Hour <=5)
          //      date = date.AddHours(-5);
            return date;
        }

        public static int ParseParam(ref int? combineId)
        {
            int lineindex = (int)combineId % 100;
            combineId = combineId/100;
            return lineindex;
        }

        public void MakeingWeekDays()
        {
            int currIndex = (int)DateTime.Now.AddHours(Utils.ZoneHour).DayOfWeek;
            if (currIndex == 0)
                currIndex = 7;
            weekDays[0] = this.comm_str.YESTERDAY_LBL;
            weekDays[1] = this.comm_str.TODAY_LBL;
            weekDays[2] = this.comm_str.TOMORROW_LBL;

            weekDays[3] = GetWeekDayName(currIndex, 2);
            weekDays[4] = GetWeekDayName(currIndex, 3);
            weekDays[5] = GetWeekDayName(currIndex, 4);
            weekDays[6] = GetWeekDayName(currIndex, 5);
            weekDays[7] = GetWeekDayName(currIndex, 6);
            Onair = this.comm_str.NOWPENDING_LBL;
        }

        private string GetWeekDayName(int dayInd, int ind)
        {
            switch (dayInd)
            {
                case 1:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 3:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 4:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 5:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 6:
                            return this.comm_str.SUNDAY_LBL;
                            
                    }
                    break;
                case 2:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 3:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 4:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 5:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 6:
                            return this.comm_str.MONDAY_LBL;
                            
                    }
                    break;
                case 3:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 3:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 4:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 5:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 6:
                            return this.comm_str.TUESDAY_LBL;
                            
                    }
                    break;
                case 4:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.SATURDAY_LBL;
                            
                        case 3:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 4:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 5:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 6:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                    }
                    break;
                case 5:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.SUNDAY_LBL;
                            
                        case 3:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 4:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 5:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 6:
                            return this.comm_str.THURSDAY_LBL;
                            
                    }
                    break;
                case 6:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.MONDAY_LBL;
                            
                        case 3:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 4:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 5:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 6:
                            return this.comm_str.FRIDAY_LBL;
                            
                    }
                    break;
                case 7:
                    switch (ind)
                    {
                        case 2:
                            return this.comm_str.TUESDAY_LBL;
                            
                        case 3:
                            return this.comm_str.WEDNESDAY_LBL;
                            
                        case 4:
                            return this.comm_str.THURSDAY_LBL;
                            
                        case 5:
                            return this.comm_str.FRIDAY_LBL;
                            
                        case 6:
                            return this.comm_str.SATURDAY_LBL;
                            
                    }
                    break;
            }
            return "";
        }
    }

    public class ProgsShowList
    {
        public string Time { get; set; }
        public DateTime Date { get; set; }
        public string Name { get; set; }
        public short? CatID { get; set; }

    }

    public class ChannelShowList
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string ImgUrl { get; set; }
        public string FBImgUrl { get; set; }
        public string DispName { get; set; }
        public string StreamUrl { get; set; }
        public int CatID { get; set; }
        public string MetaDescription { get; set; }
        public string TorrentContentID { get; set; }
        
    }

    public class ProgCategory
    {
        public string CatName { get; set; }
        public short CatId { get; set; }
        public string CatDispName { get; set; }
        public string color { get; set; }
    }

    public class NowRunningProg
    {
        public short CategoryId { get; set; }
        public DateTime Date { get; set; }
        public string PrName { get; set; }
        public string ChName { get; set; }
        public string ChdispName { get; set; }
        public int chID { get; set; }
        public string ChimgUrl { get; set; }
        public string FBImgUrl { get; set; }
        public string viewlink { get; set; }     
    }

    public class FootballData
    {
        public DateTime Date { get; set; }
        public string TeamLeft { get; set; }
        public string TeamRight { get; set; }
        
    }

}